#include <string>
#include <iostream>
#include <memory>
#include <vector>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>

#include "Util.hpp"
#include "Sock.hpp"
#include "Server.hpp"


// web根目录
#define ROOT "./wwwroot" 
#define HOMEPAGE "index.html"


static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " port\n"
              << std::endl;
}



void HandlerHttpRequest(int sockfd)
{
    char buffer[10240];
    ssize_t s =recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if(s > 0)
    {
        buffer[s] = 0 ;
    }

    // 截取出访问的文件地址

    std::vector<std::string> vline ; 
    Util::cusString(buffer,"\n",&vline);

    std::vector<std::string> vblock ; 
    Util::cusString(vline[0], " ", &vblock);

    std::string file = vblock[1];
    std::string target = ROOT;

    // ? ? ? ? ? ? 
    //     / 默认为访问 /index.html
    if(file == "/")
    {
        file = "/index.html";
    }
    target += file ; 
    std::cout << target << std::endl ; 


    //用户看到的内容

    std::string content ;
    std::ifstream in(target); //std::ifstream是C++标准库中的一个输入文件流类
    if(in.is_open())
    {
        std::string line ; 
        while(std::getline(in, line))
        {
            content += line ;
        }
    }

    std::string HttpResponse ; 
    if(content.empty())
    {
        HttpResponse = "HTTP/1.1 404 notFound\r\n" ;
    }
    else
    {
        HttpResponse = "HTTP\1.1 200 OK\r\n";
    }

    HttpResponse += "\r\n" ;
    HttpResponse += content; 

    send(sockfd, HttpResponse.c_str(), HttpResponse.size(), 0);

}


int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::unique_ptr<HttpServer> httpServer(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    httpServer->Start();
    return 0 ;
}






